#include <string>
#include <vector>
#include <iostream>
#include "curl/curl.h"
#include "ajson5.h"
#include <fstream>
#include "wstringutils.h"
#include "dockercurloperator.h"

using namespace std;
using namespace ArduinoJson;



int main(int argc, char* argv[] ) {
	cout<<"A demo program to demonstrate how to run docker stuff in c++ with libcurl."<<endl ;
	cout<<"v1.0.0.0 2023-9-21"<<endl ;
	cout<<"v1.0.0.4 2023-10-26"<<endl;
	cout<<"usage:test_curldockerapi <docker_img_name> <vcontainerdir:vhostdir> <commands> <log_filename>"<<endl ;
	cout<<"usage:test_curldockerapi u18gdal ''/home/hadoop:/home/hadoop'' ''/bin/sh /some/dir/run.sh''  /some/dir/run.log "<<endl ;

	if( argc!=5 ) {
		cout<<"Error, argc not 5, exit"<<endl ;
		return 11 ;
	}

	string imageName = argv[1];
	string volume = argv[2];//it is a demo program, so only support bind one volume.
	string command = argv[3] ;
	string logfilename = argv[4] ;

	cout<<"inputs:"<<endl ;
	cout<<"imageName "<<imageName <<endl;
	cout<<"volume "<<volume <<endl;
	cout<<"command "<<command <<endl;
	cout<<"logfilename "<<logfilename <<endl;


	DockerCurlOperator docker ;

	bool imageOk = docker.isImageExists(imageName) ;
	if( imageOk==false ) {
		cout<<"Error, not image "<<imageName<<endl ;
		return 13 ;
	}
	cout<<"Info: found docker image."<<endl ;

	vector<string> volumeTokens = wStringUtils::splitString(volume,":") ;
	if( volumeTokens.size()!=2 ) {
		cout<<"Error, volumeTokens.size()!=2 is invalid, you can only use one pair of TartetDir:SourceDir."<<endl;
		return 14 ;
	}

	vector<DockerMount> mounts ;
	mounts.push_back( DockerMount(volumeTokens[0],volumeTokens[1],false) ) ;


	//string testCommand = "/usr/bin/gdal_translate -of PNG -b 3 -b 2 -b 1 /home/hadoop/datas/FY3D-MERSI/fy3d_acv3_20230710_0620.tif /home/hadoop/datas/FY3D-MERSI/testdockerout.png " ; //this is ok

	//string testCommand = "/bin/sh /home/hadoop/coding/test_curldockerapi/dockertestrun.sh " ;//this is ok
	vector<string> commandTokens = wStringUtils::splitString(command," ") ;
	
	//string logfilename = "/home/hadoop/temp-docker.log" ;

	string error ;
	bool runok = docker.runCommandsAndRemove(
		imageName,
		mounts,
		logfilename,
		commandTokens,
		error
		) ;

	if( runok==false ) {
		cout<<"error "<<endl ;
		cout<<error<<endl ;
	}
	cout<<"runok : "<<runok<<endl ;

	cout<<"done"<<endl ;
	return 0 ;
}